<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Scrapy,">










<meta name="description" content="本文为慕课网《Python分布式爬虫打造搜索引擎》第五章的学习笔记，主要内容为scrapy爬取知名问答网站 视频地址：https://coding.imooc.com/class/92.html">
<meta name="keywords" content="Scrapy">
<meta property="og:type" content="article">
<meta property="og:title" content="【第五章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名问答网站">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/08/09/python-distributed-spider-5/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网《Python分布式爬虫打造搜索引擎》第五章的学习笔记，主要内容为scrapy爬取知名问答网站 视频地址：https://coding.imooc.com/class/92.html">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190810054733938.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190810055524474.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190810055143068.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190810061240886.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190817060434212.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190817062706472.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190817062756979.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190817071039366.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190818055142310.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190818060134975.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190818062035701.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190818061839261.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190819054153370.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190819060245334.jpg">
<meta property="og:updated_time" content="2020-01-13T02:22:07.403Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第五章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名问答网站">
<meta name="twitter:description" content="本文为慕课网《Python分布式爬虫打造搜索引擎》第五章的学习笔记，主要内容为scrapy爬取知名问答网站 视频地址：https://coding.imooc.com/class/92.html">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190810054733938.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/08/09/python-distributed-spider-5/">





  <title>【第五章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名问答网站 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/08/09/python-distributed-spider-5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第五章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名问答网站</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-08-09T16:54:27+08:00">
                2019-08-09
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网《Python分布式爬虫打造搜索引擎》第五章的学习笔记，主要内容为scrapy爬取知名问答网站</p>
<p>视频地址：<a href="https://coding.imooc.com/class/92.html" target="_blank" rel="noopener">https://coding.imooc.com/class/92.html</a></p>
<a id="more"></a>

<p><strong>注意： 虽然selenium提供了很多选择selector的API，<br>但提取页面元素时，仍然建议使用Scrapy selector的方式，因为这种方式是使用lxml库实现，它是C语言编写的，而selenium是纯Python语言编写的，速度上的差距很大。<br>只要在要操控页面元素的情况下，才使用selenium的API提取页面元素。</strong></p>
<h1 id="session与cookie的基础知识"><a href="#session与cookie的基础知识" class="headerlink" title="session与cookie的基础知识"></a>session与cookie的基础知识</h1><h2 id="Http协议"><a href="#Http协议" class="headerlink" title="Http协议"></a>Http协议</h2><p>Http是一种无状态的协议，即无法标记不同的用户</p>
<p><img src="/blog/images/20190810054733938.jpg" alt="Http协议"></p>
<h2 id="session和cookie机制"><a href="#session和cookie机制" class="headerlink" title="session和cookie机制"></a>session和cookie机制</h2><ol>
<li><p>cookie用一种类似dict的存储方式存储数据，如{‘key’:’value’}<br><img src="/blog/images/20190810055524474.jpg" alt="cookie存储方式"></p>
</li>
<li><p>cookie工作机制</p>
<blockquote>
<p>通过cookie存储id实现用户标记，并且这个id就是session id</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20190810055143068.jpg" alt="cookie工作机制"></p>
<ol start="3">
<li>服务端为不同用户生成唯一的session，并随response将session id返回给浏览器，浏览器通过cookie将这个session id存储到本地，<br>每次浏览器请求时，都会带上这个session id到服务端，用于标记不同用户，直到session过期为止</li>
</ol>
<h2 id="常见HTTP状态码"><a href="#常见HTTP状态码" class="headerlink" title="常见HTTP状态码"></a>常见HTTP状态码</h2><p><img src="/blog/images/20190810061240886.jpg" alt="常见HTTP状态码"></p>
<h1 id="selenium的安装与使用"><a href="#selenium的安装与使用" class="headerlink" title="selenium的安装与使用"></a>selenium的安装与使用</h1><blockquote>
<p>selenium是浏览器自动化测试框架，Selenium测试直接运行在浏览器中，就像真正的用户在操作一样。支持的浏览器包括IE（7, 8, 9, 10, 11），Mozilla Firefox，Safari，Google Chrome，Opera等。 摘录自：百度百科：<a href="https://baike.baidu.com/item/selenium/18266" target="_blank" rel="noopener">https://baike.baidu.com/item/selenium/18266</a></p>
</blockquote>
<ol>
<li>安装selenium<br>在虚拟环境下执行如下命令：<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip <span class="keyword">install</span> selenium</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190817060434212.jpg" alt="安装selenium"></p>
<ol start="2">
<li><p>selenium API文档<br>英文：<a href="https://selenium-python.readthedocs.io/" target="_blank" rel="noopener">https://selenium-python.readthedocs.io/</a><br>中文：<a href="https://selenium-python-zh.readthedocs.io/en/latest/api.html" target="_blank" rel="noopener">https://selenium-python-zh.readthedocs.io/en/latest/api.html</a></p>
</li>
<li><p>下载Chrome的Driver<br><a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" target="_blank" rel="noopener">https://sites.google.com/a/chromium.org/chromedriver/downloads</a></p>
</li>
<li><p>编写代码</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> selenium import webdriver</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 生成浏览器对象</span></span><br><span class="line">browser = webdriver.Chrome(</span><br><span class="line">    <span class="attribute">executable_path</span>=<span class="string">"D:/gxg/dev/chromedriver_win32_for_76/chromedriver.exe"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 打开网页并下载网页内容</span></span><br><span class="line">browser.<span class="builtin-name">get</span>(<span class="string">"https://www.baidu.com/"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 打印网页内容 = F12看到的内容 != 右键源代码的内容</span></span><br><span class="line"><span class="builtin-name">print</span>(browser.page_source)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 注意： 虽然selenium提供了很多选择selector的API，</span></span><br><span class="line"><span class="comment"># 但提取页面元素时，仍然建议使用Scrapy selector的方式，因为这种方式是使用lxml库实现，它是C语言编写的，</span></span><br><span class="line"><span class="comment"># 而selenium是纯Python语言编写的，速度上的差距很大。</span></span><br><span class="line"><span class="comment"># 只要在要操控页面元素的情况下，才使用selenium的API提取页面元素。</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 1. 提取页面元素：</span></span><br><span class="line">t_selector = Selector(<span class="attribute">text</span>=browser.page_source)</span><br><span class="line"><span class="builtin-name">print</span>(t_selector.css(<span class="string">".qrcode-text .sub-title::text"</span>).extract())</span><br><span class="line"></span><br><span class="line"><span class="comment"># 2. 操控页面元素：输入关键字“python”并点击搜索按钮</span></span><br><span class="line">browser.find_element_by_id(<span class="string">"kw"</span>).send_keys(<span class="string">"Python"</span>)</span><br><span class="line">browser.find_element_by_id(<span class="string">"su"</span>).click()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 关闭浏览器</span></span><br><span class="line">browser.quit()</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190817062706472.jpg" alt="安装selenium"><br><img src="/blog/images/20190817062756979.jpg" alt="安装selenium"></p>
<p>注意： 虽然selenium提供了很多选择selector的API，但提取页面元素时，仍然建议使用Xpath的方式，因为这种方式是使用C语言编写的，而selenium是纯Python语言编写的，速度上的差距很大。<br>只要在要操控页面元素的情况下，才使用selenium的API提取页面元素。</p>
<h1 id="通过selenium模拟登录知乎"><a href="#通过selenium模拟登录知乎" class="headerlink" title="通过selenium模拟登录知乎"></a>通过selenium模拟登录知乎</h1><h2 id="通过selenium模拟登录知乎-1"><a href="#通过selenium模拟登录知乎-1" class="headerlink" title="通过selenium模拟登录知乎"></a>通过selenium模拟登录知乎</h2><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">zhihu_url = <span class="string">"https://www.zhihu.com/signin?next=%2F"</span></span><br><span class="line">browser = webdriver.<span class="type">Chrome</span>(</span><br><span class="line">    executable_path=<span class="string">"D:/gxg/dev/chromedriver_win32_for_76/chromedriver.exe"</span>)</span><br><span class="line"></span><br><span class="line">browser.get(zhihu_url)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 点击切换到使用用户名和密码登录</span></span><br><span class="line">browser.find_element_by_xpath('//*[@id=<span class="string">"root"</span>]/<span class="keyword">div</span>/main/<span class="keyword">div</span>/<span class="keyword">div</span>/<span class="keyword">div</span>[<span class="number">2</span>]/<span class="keyword">div</span>/form/<span class="keyword">div</span>[<span class="number">1</span>]/<span class="keyword">div</span>[<span class="number">2</span>]').click()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输入用户名和密码</span></span><br><span class="line">browser.find_element_by_css_selector(<span class="string">".SignFlow-accountInput input[name='username']"</span>).send_keys(<span class="string">"xxxxx"</span>)</span><br><span class="line">browser.find_element_by_css_selector(<span class="string">".SignFlow-password input[name='password']"</span>).send_keys(<span class="string">"xxxxx"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 点击登录</span></span><br><span class="line">browser.find_element_by_css_selector(<span class="string">".SignFlow-submitButton"</span>).click()</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190817071039366.jpg" alt="模拟登录知乎"></p>
<h2 id="知乎倒立文字识别"><a href="#知乎倒立文字识别" class="headerlink" title="知乎倒立文字识别"></a>知乎倒立文字识别</h2><h2 id="selenium自动识别验证码完成模拟登录"><a href="#selenium自动识别验证码完成模拟登录" class="headerlink" title="selenium自动识别验证码完成模拟登录"></a>selenium自动识别验证码完成模拟登录</h2><h1 id="通过request模拟登录知乎"><a href="#通过request模拟登录知乎" class="headerlink" title="通过request模拟登录知乎"></a><del>通过request模拟登录知乎</del></h1><pre><code>现在通过这种方式已经无法登陆知乎，但这种思想是通用的
登录知乎只能使用上述一节中&quot;通过selenium模拟登录知乎&quot;的方式，登录其他网站仍可使用如下方式</code></pre><h2 id="分析登录时post的数据和url"><a href="#分析登录时post的数据和url" class="headerlink" title="分析登录时post的数据和url"></a>分析登录时post的数据和url</h2><p><img src="/blog/images/20190818055142310.jpg" alt="分析登录时post的数据和url"></p>
<h2 id="安装requests库"><a href="#安装requests库" class="headerlink" title="安装requests库"></a>安装requests库</h2><p><img src="/blog/images/20190818060134975.jpg" alt="安装requests库"></p>
<p>requests库API：<a href="http://2.python-requests.org/zh_CN/latest/user/quickstart.html" target="_blank" rel="noopener">http://2.python-requests.org/zh_CN/latest/user/quickstart.html</a></p>
<h2 id="设置user-agent信息"><a href="#设置user-agent信息" class="headerlink" title="设置user-agent信息"></a>设置user-agent信息</h2><p>直接使用request访问url，可能会报出500的错误，如下图：<br><img src="/blog/images/20190818062035701.jpg" alt="requests库500的错误"></p>
<p>这些因为，request通过get方式访问url时，默认的user-agent是python2或python3，有的服务器判断为此就会认为是爬虫而拒绝它的访问<br><img src="/blog/images/20190818061839261.jpg" alt="获取user-agent信息"></p>
<p>解决方法就是手动设置user-agent:</p>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment"># 设置user-agent</span></span><br><span class="line">agent = <span class="string">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"</span></span><br><span class="line">header = &#123;</span><br><span class="line">    <span class="string">"HOST"</span>: <span class="string">"www.zhihu.com"</span>,</span><br><span class="line">    <span class="string">"Referer"</span>: <span class="string">"https://www.zhihu.com"</span>,</span><br><span class="line">    <span class="string">"User-Agent"</span>: agent</span><br><span class="line">&#125;</span><br><span class="line">response = requests.get(<span class="string">"http://www.zhihu.com"</span>, headers=header)</span><br><span class="line">print(response.text)</span><br></pre></td></tr></table></figure>

<h2 id="判断用户是否为登录状态"><a href="#判断用户是否为登录状态" class="headerlink" title="判断用户是否为登录状态"></a>判断用户是否为登录状态</h2><p><img src="/blog/images/20190819054153370.jpg" alt="判断用户是否为登录状态"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 判断用户是否为登录状态</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">is_login</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">        通过访问个人中心页面的状态码来判断用户的登录状态</span></span><br><span class="line"><span class="string">    :return:</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    inbox_url = <span class="string">"https://www.zhihu.com/inbox"</span></span><br><span class="line">    <span class="comment"># 通过allow_redirects禁止重定向跳转，默认时允许重定向跳转的，此时无法返回302的状态码</span></span><br><span class="line">    response = session.get(inbox_url, headers=header, allow_redirects=<span class="literal">False</span>)</span><br><span class="line">    <span class="keyword">if</span> response.status_code != <span class="number">200</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br></pre></td></tr></table></figure>

<h1 id="通过scrapy爬取知乎"><a href="#通过scrapy爬取知乎" class="headerlink" title="通过scrapy爬取知乎"></a>通过scrapy爬取知乎</h1><h2 id="新建知乎的spider"><a href="#新建知乎的spider" class="headerlink" title="新建知乎的spider"></a>新建知乎的spider</h2><p>新建知乎的spider的命令如下：</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">cd ArticleSpider</span><br><span class="line">scrapy genspider zhihu www<span class="selector-class">.zhihu</span><span class="selector-class">.com</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190819060245334.jpg" alt="新建知乎的spider"></p>
<h2 id="爬取知乎页面的第一步——登录知乎"><a href="#爬取知乎页面的第一步——登录知乎" class="headerlink" title="爬取知乎页面的第一步——登录知乎"></a><del>爬取知乎页面的第一步——登录知乎</del></h2><blockquote>
<p>如下代码实现登录知乎已经无效，但原理是通用的。 登录知乎只能使用上述一节中”通过selenium模拟登录知乎”的方式，登录其他网站仍可使用如下方式<br>cookie会在整个Scrapy内部自动传递，无需手动设置</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> scrapy</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">import</span> json</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ZhihuSpider</span><span class="params">(scrapy.Spider)</span>:</span></span><br><span class="line">    name = <span class="string">'zhihu'</span></span><br><span class="line">    allowed_domains = [<span class="string">'www.zhihu.com'</span>]</span><br><span class="line">    start_urls = [<span class="string">'http://www.zhihu.com/'</span>]</span><br><span class="line">    <span class="comment"># 设置user-agent</span></span><br><span class="line">    agent = <span class="string">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"</span></span><br><span class="line">    header = &#123;</span><br><span class="line">        <span class="string">"HOST"</span>: <span class="string">"www.zhihu.com"</span>,</span><br><span class="line">        <span class="string">"Referer"</span>: <span class="string">"https://www.zhihu.com"</span>,</span><br><span class="line">        <span class="string">"User-Agent"</span>: agent</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="string">"""解析登录成功后的start_urls页面"""</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse_detail</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""具体的页面解析逻辑"""</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 爬取知乎的第一步：登录知乎</span></span><br><span class="line">    <span class="comment"># Scrapy的Spider的入口方法：start_requests，</span></span><br><span class="line">    <span class="comment"># 所以要重写start_requests方法来登录知乎</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">start_requests</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            通过异步IO方式，先访问登录页面获取页面数据， 然后通过回调函数调用login方法</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="keyword">return</span> [scrapy.request(<span class="string">"http://www.zhihu.com/#signin"</span>,</span><br><span class="line">                               headers=self.header, callback=self.login)]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="comment"># 正则表达式匹配多行：re.DOTALL</span></span><br><span class="line">        match_obj = re.match(<span class="string">'.*name="_xsrf" value="(.*?)"'</span>, response.text, re.DOTALL)</span><br><span class="line">        xsrf = <span class="string">""</span></span><br><span class="line">        <span class="keyword">if</span> match_obj:</span><br><span class="line">            xsrf = match_obj.group(<span class="number">1</span>)</span><br><span class="line">            <span class="comment"># scrapy.FormRequest: 完成表单提交功能，即登录操作</span></span><br><span class="line">            <span class="keyword">return</span> [scrapy.FormRequest(</span><br><span class="line">                ulr=<span class="string">"http://www.zhihu.com/login/phone_num"</span>,</span><br><span class="line">                formdata=&#123;</span><br><span class="line">                    <span class="string">"_xsrf"</span>: xsrf,</span><br><span class="line">                    <span class="string">"phone_num"</span>: <span class="string">"18782902568"</span>,</span><br><span class="line">                    <span class="string">"password"</span>: <span class="string">"admin123"</span></span><br><span class="line">                &#125;,</span><br><span class="line">                headers=self.header,</span><br><span class="line">                <span class="comment"># 回调函数判断是否登录成功</span></span><br><span class="line">                callback=self.check_login</span><br><span class="line">            )]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">check_login</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            验证服务器返回状态来判断用户的登录成功，成功则再执行start_requests默认的逻辑</span></span><br><span class="line"><span class="string">        :param response:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        text_json = json.load(response.text)</span><br><span class="line">        <span class="keyword">if</span> <span class="string">"msg"</span> <span class="keyword">in</span> text_json <span class="keyword">and</span> text_json[<span class="string">"msg"</span>] == <span class="string">"登录成功"</span>:</span><br><span class="line">            <span class="comment"># 此处再执行start_requests默认的逻辑</span></span><br><span class="line">            <span class="keyword">for</span> url <span class="keyword">in</span> self.start_urls:</span><br><span class="line">                <span class="comment"># 默认的回调函数为： parse</span></span><br><span class="line">                <span class="keyword">yield</span> scrapy.Request(url, dont_filter=<span class="literal">True</span>, headers=self.header)</span><br></pre></td></tr></table></figure>

<p>/code/article_scrapy</p>
<h2 id="爬取知乎页面的第二步——页面分析及数据表设计"><a href="#爬取知乎页面的第二步——页面分析及数据表设计" class="headerlink" title="爬取知乎页面的第二步——页面分析及数据表设计"></a>爬取知乎页面的第二步——页面分析及数据表设计</h2><h2 id="爬取知乎页面的第三步——解析页面"><a href="#爬取知乎页面的第三步——解析页面" class="headerlink" title="爬取知乎页面的第三步——解析页面"></a>爬取知乎页面的第三步——解析页面</h2>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Scrapy/" rel="tag"># Scrapy</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/08/08/how-to-use-form-select-by-jq/" rel="next" title="jquery操作select标签change事件与获取选中option的值">
                <i class="fa fa-chevron-left"></i> jquery操作select标签change事件与获取选中option的值
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/08/13/tensorFlow-step-by-step-2/" rel="prev" title="【第二章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow-keras实战">
                【第二章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow-keras实战 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#session与cookie的基础知识"><span class="nav-number">1.</span> <span class="nav-text">session与cookie的基础知识</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Http协议"><span class="nav-number">1.1.</span> <span class="nav-text">Http协议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#session和cookie机制"><span class="nav-number">1.2.</span> <span class="nav-text">session和cookie机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常见HTTP状态码"><span class="nav-number">1.3.</span> <span class="nav-text">常见HTTP状态码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#selenium的安装与使用"><span class="nav-number">2.</span> <span class="nav-text">selenium的安装与使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#通过selenium模拟登录知乎"><span class="nav-number">3.</span> <span class="nav-text">通过selenium模拟登录知乎</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#通过selenium模拟登录知乎-1"><span class="nav-number">3.1.</span> <span class="nav-text">通过selenium模拟登录知乎</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#知乎倒立文字识别"><span class="nav-number">3.2.</span> <span class="nav-text">知乎倒立文字识别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#selenium自动识别验证码完成模拟登录"><span class="nav-number">3.3.</span> <span class="nav-text">selenium自动识别验证码完成模拟登录</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#通过request模拟登录知乎"><span class="nav-number">4.</span> <span class="nav-text">通过request模拟登录知乎</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#分析登录时post的数据和url"><span class="nav-number">4.1.</span> <span class="nav-text">分析登录时post的数据和url</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装requests库"><span class="nav-number">4.2.</span> <span class="nav-text">安装requests库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置user-agent信息"><span class="nav-number">4.3.</span> <span class="nav-text">设置user-agent信息</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#判断用户是否为登录状态"><span class="nav-number">4.4.</span> <span class="nav-text">判断用户是否为登录状态</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#通过scrapy爬取知乎"><span class="nav-number">5.</span> <span class="nav-text">通过scrapy爬取知乎</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#新建知乎的spider"><span class="nav-number">5.1.</span> <span class="nav-text">新建知乎的spider</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#爬取知乎页面的第一步——登录知乎"><span class="nav-number">5.2.</span> <span class="nav-text">爬取知乎页面的第一步——登录知乎</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#爬取知乎页面的第二步——页面分析及数据表设计"><span class="nav-number">5.3.</span> <span class="nav-text">爬取知乎页面的第二步——页面分析及数据表设计</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#爬取知乎页面的第三步——解析页面"><span class="nav-number">5.4.</span> <span class="nav-text">爬取知乎页面的第三步——解析页面</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
